package org.duang.http.core;

import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.nio.client.HttpAsyncClient;
import org.duang.http.common.ClientException;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultServiceClient extends ServiceClient {
	
	private static Logger logger = LoggerFactory.getLogger(DefaultServiceClient.class);
	private static HttpAsyncClient httpClient;
	private boolean clientIsOpen;
	private static PoolingNHttpClientConnectionManager connManager;
	
	public static HttpAsyncClient getHttpClient() {
//		HttpClientBuilder.create().setConnectionManager(connManager).build();
		return httpClient;
	}
	
	public DefaultServiceClient() {
		super();
		clientIsOpen = false;
		try{
			connManager = HttpFactory.getConnectionManager(config);
			httpClient = HttpFactory.createHttpAsyncClient(connManager, config);
			start();		//启动
		} catch (Exception e) {
			e.printStackTrace();
			logger.warn(e.getMessage());
			close();
			throw new ClientException(e.getMessage(),e);
		}
	}
	
	 @Override
	    public boolean isStart() {
	        return clientIsOpen;
	    }
	 
	protected <T> Future<HttpResponse> sendRequestImpl(Request request, HttpCallBack<T> callback) throws Exception {
		if(ToolsKit.isEmpty(request) && ToolsKit.isEmpty(request.getContent())){
			throw new ClientException("request or content is null");
		}
		HttpRequestBase httpRequest = HttpFactory.createHttpRequest(request);
		return  httpClient.execute(httpRequest, callback);
//		Future<HttpResponse> future = httpClient.execute(httpRequest, callback);			
//		httpRequest.releaseConnection(); //这个不用开注释
//		return future;
	}
	
	public void start() {
		if (ToolsKit.isNotEmpty(httpClient) && httpClient instanceof CloseableHttpAsyncClient && !clientIsOpen) {
			try{
				// 启动一个线程清理闲置和过期的连接
				HttpFactory.IdleConnectionMonitor.getInstance().addConnMgr(connManager);
				((CloseableHttpAsyncClient)httpClient).start();
				clientIsOpen = true;
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			}
		}
		
	}
	
	public void close() {
		if (ToolsKit.isNotEmpty(httpClient) && httpClient instanceof CloseableHttpAsyncClient) {
			try{
				((CloseableHttpAsyncClient)httpClient).close();
				HttpFactory.IdleConnectionMonitor.getInstance().removeConnMgr(connManager);
                clientIsOpen = false;
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			}
		}
	}
}
